#include "utilities.h"
#include "db.h"

#define LINE_LENGTH (LABLE_MAX_LENGTH + (outLineLength/2) + 3)
#define LINE_NUMBER_LENGTH 4

/* print the address of the lible */
static void printAddress(char *line,FILE *codeOut, int lineNumber);

/* print the line number */
static void printLineNumber(int lineNumber, FILE *codeOut);

void pass2(char *filename)
{
	int lineNumber = 0;
	char line[LINE_LENGTH];
	FILE *codeIn;
	FILE *codeOut;
	
	codeIn = openFile(filename,".ob1","r");
	codeOut = openFile(filename,".ob","w");
	
	while(fgets(line, LINE_LENGTH, codeIn) != NULL)
	{
		if(isdigit(line[0]))
		{
			printLineNumber(lineNumber,codeOut);
			fprintf(codeOut,"%s",line);
			lineNumber++;
			continue;
		}
		
		printAddress(line,codeOut, lineNumber);
		lineNumber++;
	}
	
	listFree(lable_list);
	fclose(codeIn);
	fclose(codeOut);
}

/* print the address of the lible */
static void printAddress(char *line,FILE *codeOut, int lineNumber)
{
	char *charp;
	char *sAd;
	node_ptr p;
	
	charp = line;
	while(!isspace(*charp))
	{
		charp++;
	}
	*charp = '\0';
	charp ++;

	p = list_find(lable_list,line);
	if(p == NULL)
	{
		do_lable_error(line);
		return;
	}
	
	printLineNumber(lineNumber,codeOut);
	
	sAd = toCharArray(p->value);
	printLineAt4Base(sAd,codeOut);
	free(sAd);
	
	fputc(' ',codeOut);
	while(*charp != '\0')
	{
		fputc(*charp,codeOut);
		charp++;
	}
}

/* print the line number */
static void printLineNumber(int lineNumber, FILE *codeOut)
{
	int num;
	int i;
	char *sLN;
	char ch;
	
	i = outLineLength  - LINE_NUMBER_LENGTH*2;
	sLN = toCharArray(lineNumber);
	while(i<outLineLength)
	{
		num = 0;
		num += (sLN[i]-'0')*2;
		i++;
		num += (sLN[i]-'0');
		i++;
		ch = num + '0';
		fputc(ch,codeOut);
	}
	fputc(' ',codeOut);
	free(sLN);
}